package bg.uni_sofia.conf_manager.mail;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.apache.jasper.tagplugins.jstl.core.If;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import bg.uni_sofia.conf_manager.beans.EmployeeBean;
import bg.uni_sofia.conf_manager.beans.LectureBean;
import bg.uni_sofia.conf_manager.beans.LoginBean;
import bg.uni_sofia.conf_manager.model.Employee;
import bg.uni_sofia.conf_manager.model.Lecture;
import bg.uni_sofia.conf_manager.model.Lecturer;

@Stateless
public class SendMsgOnTimeJob implements Job {
	
	private EntityManagerFactory emf = Persistence.createEntityManagerFactory("ConferenceDB");
	EntityManager em = emf.createEntityManager();
	
	@Inject
	LoginBean sesData;
	
	@Inject
	LectureBean lectureBean;
	
	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		
		
		TypedQuery<Lecture> query = em.createNamedQuery("getLecturesByStatus",
				Lecture.class);
		query.setParameter("status", 1);
		List<Lecture> lectureApproved = query.getResultList();
		List<Lecture> yesterdayLectures = new ArrayList<>();
		if(lectureApproved.size() != 0){
			for(Lecture lecture: lectureApproved){
				Date now = new Date();
				long timeDiff = now.getTime() - lecture.getLastModified().getTime();
				long timeDiffDays = timeDiff/(1000 * 60 * 60 * 24);
				if (timeDiffDays == 1) {
					yesterdayLectures.add(lecture);
				}
			}
		}
		
		
		StringBuilder msgList = new StringBuilder();
		msgList.append("This is the list with approved lectures for yesterday:\n");
		if (yesterdayLectures.size() != 0) {
			for(Lecture lec: yesterdayLectures){
				msgList.append("Lecture " + lec.getTitle() + " on " + lec.getDate() + " at " + lec.getTime() + "\n");
			}
		}else{
			msgList.append("there are no approved lectures");
		}
		
		TypedQuery<Lecturer> queryL = em.createNamedQuery("getAllLecturers", Lecturer.class);
		queryL.setParameter("isActive", true);
		List<Lecturer> lecturerList = queryL.getResultList();
		if (lecturerList.size() != 0) {
			for (Lecturer lecturer: lecturerList) {
				StringBuilder msg = new StringBuilder();
				msg.append("Dear, " + lecturer.getName() + "\n");
				msg.append(msgList);
				msg.append("\n Best regards \n ConfinderenceTeam!");
				
				Mail.sendMail(lecturer.getEmail(), "Confinderence: List with approved lectures.", msg.toString());
			}
		}
		
		
	}

}
